package org.blim.blackdawn.graph;

import android.opengl.Matrix;
import android.os.SystemClock;

/**
 * UniformAnimation rotates around the x, y and z axes by a specified rate.  It
 * uses the system uptime as the absolute reference.
 * 
 * @author lee@longlost.info
 */
public class UniformAnimation implements Animation {

	private final long mRotRateX;
	private final long mRotRateY;
	private final long mRotRateZ;

	public UniformAnimation(long rotRateX, long rotRateY, long rotRateZ) {
		mRotRateX = rotRateX;
		mRotRateY = rotRateY;
		mRotRateZ = rotRateZ;
	}
	
	@Override
	public float[] getAnimationMatrix() {
		float[] result = new float[16];
		long time = SystemClock.uptimeMillis();
		
	    float xAngle = calculateAngle(time, mRotRateX);
	    float yAngle = calculateAngle(time, mRotRateY);
	    float zAngle = calculateAngle(time, mRotRateZ);
	    
	    // TODO: Make more efficient.
		Matrix.setIdentityM(result, 0);
		Matrix.rotateM(result, 0, xAngle, 1.0f, 0.0f, 0.0f);
		Matrix.rotateM(result, 0, yAngle, 0.0f, 1.0f, 0.0f);
		Matrix.rotateM(result, 0, zAngle, 0.0f, 0.0f, 1.0f);
		
		return result;
	}

	private float calculateAngle(long time, long rate) {
		if (rate != 0) {
			long pos = time % Math.abs(rate); 
			
			return (360.0f / rate) * ((int) pos);
		} else {
			return 0;
		}
	}
	
}
